<template>
  <el-form ref="formRef" :model="form" labelWidth="120px" label-suffix="：">
    <el-steps :active="active">
      <template v-for="(step, index) in steps" :key="index">
        <el-step>
          <template #title>
            <span class="step-title" @click="active = step.value">{{ step.title }}</span>
          </template>
        </el-step>
      </template>
    </el-steps>
    <div v-show="active === 1" class="step1">
      <el-form-item label="节点名称">
        <el-input v-model="form.nodeName"/>
      </el-form-item>
      <el-form-item label="节点ID">
        <el-input v-model="form.typeConcatName" disabled/>
      </el-form-item>
      <el-form-item label="流输出" prop="isStream">
        <el-switch v-model="form.isStream" active-value="Y" inactive-value="N"></el-switch>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
      <dialog-footer @cancel="cancel" @ok="submitForm" ok-text="保存">
        <el-button type="success" @click="active = 2">下一步</el-button>
      </dialog-footer>
    </div>
    <div v-show="active === 2" class="step2">

      <el-form-item label="创建新脚本">
        <el-radio-group v-model="form.selectScriptStatus" @change="changeScriptStatus">
          <el-radio label="是"/>
          <el-radio label="否，选择已有脚本"/>
        </el-radio-group>
      </el-form-item>
<!--        <el-form-item label="脚本名称" v-show="selectScriptStatus === '是'">-->
<!--          <el-input v-model="form.newScriptName"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="类名" v-show="selectScriptStatus === '是'">-->
<!--          <el-input v-model="form.newClassName"/>-->
<!--        </el-form-item>-->
      <el-form-item label="选择脚本" v-if="form.selectScriptStatus === '否，选择已有脚本'">
        <el-select v-model="form.scriptName" @change="handleScriptChange">
          <el-option
              v-for="item in scriptList"
              :key="item.id"
              :label="item.scriptName"
              :value="item.scriptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Java代码">
        <monaco-editor style="width:100%; height:400px"
                       v-model:value="form.scriptContext"
                       @changeTextArea="changeTextArea"
                       ref="monacoEditorRef"
                       class="script-textarea"
                       language='java'
        ></monaco-editor>
      </el-form-item>
      <dialog-footer @ok="submitForm" @cancel="cancel" ok-text="保存">
        <el-button type="success" @click="active = 1">上一步</el-button>
      </dialog-footer>
    </div>
  </el-form>
</template>

<script setup>
import {defineComponent, nextTick, onMounted, reactive, ref} from 'vue';
import {flowServiceStore} from '@data/store/flow';
import {storeToRefs} from 'pinia';
import monacoEditor from "../disposition/monaco-editor.vue";
import {search, insert, deleteByIds, updateById, selectById,getDefaultScript} from "@data/api/data/datascript";

const flowCount = flowServiceStore();

const {flowData} = storeToRefs(flowCount);

const steps = ref([
  { value: 1, title: '基础属性' },
  { value: 2, title: 'Java代码' }
]);
const active = ref(1);
const monacoEditorRef = ref(null);

defineComponent({
  name: 'UserDefinedJavaClass',
});

const queryParams = {
  pageNum: 1,
  pageSize: 10,
  // 脚本名称
  scriptName: undefined,
  // 脚本状态
  scriptStatus: '',
  // 脚本类型
  scriptType: '1',
  // 创建人
  createByLike: '',
  // 创建时间
  createTime: undefined,
  // 更新人
  updateByLike: '',
  // 更新时间
  updateTime: undefined,
};

const props = defineProps({
  detailObject: {
    type: Object,
    default: () => {
    },
  },
})

const form = reactive({
  nodeName: '',
  name: '',
  type: 'UserDefinedJavaClass',
  distribute: 'Y',
  copies: 1,
  remark: '',
  definitions: {
    definition:
      {
        class_type: '',
        class_name: '',
        class_source: ''
      }

  },
  fields: {
    field: [],
  },
  clear_result_fields: '',
  scriptContext: 'import java.util.Date;\npublic boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {\n  if (first) {\n    first = false;\n  }\n  Object[] r = getRow();\n  if (r == null) {\n    setOutputDone();\n    return false;\n  }\n  r = createOutputRow(r, data.outputRowMeta.size());\n  String foobar = get(Fields.In, \"Field_001\").getString(r);\n\n  foobar += \"bar\";\n  \n  get(Fields.Out, \"Field_002\").setValue(r, foobar);\n  get(Fields.Out, \"newColumn\").setValue(r, foobar);\n\n  long currentTimeMillis = System.currentTimeMillis();\n  Date date = new Date();\n  get(Fields.Out, \"insert_time\").setValue(r, currentTimeMillis);\n  get(Fields.Out, \"insert_time_date\").setValue(r, date);\n\n  putRow(data.outputRowMeta, r);\n\n  return true;\n}',
  scriptContextValue:'',

  selectScriptStatus: '是',

  isStream: '',

  GUI: {
    xloc: 1,
    yloc: 1,
    draw: 'Y'
  }
});

const emit = defineEmits(['cancel']);

onMounted(() => {
  form.nodeName = flowData.value[props.detailObject.id]?.nodeName || props.detailObject.data.label;
  form.name = props.detailObject.id;
  form.typeConcatName = `${props.detailObject.id}(${form.type}-${props.detailObject.id})`;
  form.definitions = flowData.value[props.detailObject.id]?.definitions || {
    definition: {}
  };
  form.fields = flowData.value[props.detailObject.id]?.fields || {
    field: []
  };
  form.remark = flowData.value[props.detailObject.id]?.remark || '';

  form.selectScriptStatus = flowData.value[props.detailObject.id]?.selectScriptStatus || '是';
  form.scriptName = flowData.value[props.detailObject.id]?.scriptName || '';
  console.log('form.scriptContext',form.scriptContext)
  console.log('form.scriptContextValue',form.scriptContextValue)
  form.scriptContext = flowData.value[props.detailObject.id]?.scriptContext || 'import java.util.Date;\npublic boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {\n  if (first) {\n    first = false;\n  }\n  Object[] r = getRow();\n  if (r == null) {\n    setOutputDone();\n    return false;\n  }\n  r = createOutputRow(r, data.outputRowMeta.size());\n  String foobar = get(Fields.In, \"Field_001\").getString(r);\n\n  foobar += \"bar\";\n  \n  get(Fields.Out, \"Field_002\").setValue(r, foobar);\n  get(Fields.Out, \"newColumn\").setValue(r, foobar);\n\n  long currentTimeMillis = System.currentTimeMillis();\n  Date date = new Date();\n  get(Fields.Out, \"insert_time\").setValue(r, currentTimeMillis);\n  get(Fields.Out, \"insert_time_date\").setValue(r, date);\n\n  putRow(data.outputRowMeta, r);\n\n  return true;\n}'
  form.scriptContextValue = flowData.value[props.detailObject.id]?.scriptContextValue || ''
  monacoEditorRef.value.setData(form.scriptContext);

  form.isStream = flowData.value[props.detailObject.id]?.isStream || '';

  form.distribute = flowData.value[props.detailObject.id]?.distribute || 'Y';

  getScript()
})

const scriptList = ref([]);
// 查询脚本列表
const getScript = () => {
  search(queryParams).then(
      response => {
        scriptList.value = response.data.list;
        console.log('scriptList.value',scriptList.value)

      }
  );
};

// 新增当前脚本索引跟踪
const currentScriptIndex = ref(-1);

const handleScriptChange = (selectedName) => {
    // 保存前一个脚本的修改
    // if(currentScriptIndex.value >= 0){
    //     const prevScript = scriptList.value[currentScriptIndex.value];
    //     prevScript.scriptContext = form.scriptContextValue;
    //     console.log(form.scriptContextValue)
    //     console.log('已保存前一个脚本修改：', prevScript);
    // }

    // 获取新选择脚本的索引
    const newIndex = scriptList.value.findIndex(  item => item.scriptName === selectedName);
    if(newIndex === -1) return;

    currentScriptIndex.value = newIndex;
    const selectedScript = scriptList.value[newIndex];

    // 更新编辑器内容
    if(monacoEditorRef.value){
      monacoEditorRef.value.setData(selectedScript.scriptContext);
      form.scriptContextValue = selectedScript.scriptContext;
    }

    console.log('scriptList',scriptList.value)
}

const changeScriptStatus = (value) => {
  form.scriptContextValue = '';
  if(value === '是'){
    form.scriptContext = 'import java.util.Date;\npublic boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {\n  if (first) {\n    first = false;\n  }\n  Object[] r = getRow();\n  if (r == null) {\n    setOutputDone();\n    return false;\n  }\n  r = createOutputRow(r, data.outputRowMeta.size());\n  String foobar = get(Fields.In, \"Field_001\").getString(r);\n\n  foobar += \"bar\";\n  \n  get(Fields.Out, \"Field_002\").setValue(r, foobar);\n  get(Fields.Out, \"newColumn\").setValue(r, foobar);\n\n  long currentTimeMillis = System.currentTimeMillis();\n  Date date = new Date();\n  get(Fields.Out, \"insert_time\").setValue(r, currentTimeMillis);\n  get(Fields.Out, \"insert_time_date\").setValue(r, date);\n\n  putRow(data.outputRowMeta, r);\n\n  return true;\n}';
  }
  else if(value === '否，选择已有脚本'){
    form.scriptContext = '';
    form.scriptName = '';
  }
  monacoEditorRef.value.setData(form.scriptContext)
}
const changeTextArea = (value) => {
  console.log('changeTextArea',value)
  form.scriptContextValue = value;
}



const submitForm = () => {
  // // 处理新建脚本逻辑
  // if (selectScriptStatus.value === '是' && form.newScriptName && form.newClassName) {
  //   const newScript = {
  //     scriptClassName: form.newScriptName,
  //     scriptContext: form.scriptContextValue,
  //     scriptType: form.newClassName,
  //   };
  //
  //   // 添加新脚本到列表
  //   scriptList.value.unshift(newScript);
  //   currentScriptIndex.value = 0; // 定位到新建的脚本
  //
  //   console.log('新建脚本:', newScript);
  // } else {
  //   // 原有保存逻辑
  //   if(currentScriptIndex.value >= 0){
  //     scriptList.value[currentScriptIndex.value].scriptContext = form.scriptContextValue;
  //   }
  // }
  // // 新增：将全部脚本信息存入definition数组
  // form.definitions.definition = scriptList.value.map(script => ({
  //   class_type: script.scriptPackageName,
  //   class_name: script.scriptClassName,
  //   class_source: script.scriptContext
  // }));
  form.scriptContext = form.scriptContextValue

  if (form.selectScriptStatus === '是') {
    console.log('scriptContext',form.scriptContext)
    // 创建新脚本时直接更新definition
    form.definitions.definition = {
      class_type: 'TRANSFORM_CLASS',  // 类名对应class_type
      class_name: 'Processor', // 脚本名称对应class_name
      class_source: form.scriptContextValue // 代码内容
    };
  } else if(currentScriptIndex.value >= 0){
      const selectedScript = scriptList.value[currentScriptIndex.value];
      // 更新当前脚本内容
      selectedScript.scriptContext = form.scriptContextValue;
      // 将选中脚本赋值给definition
    form.definitions.definition = {
      class_type: 'TRANSFORM_CLASS',
      class_name: selectedScript.scriptName,
      class_source: selectedScript.scriptContext
    };
  }

  console.log('已加载全部脚本到definitions:', form.definitions.definition);
  flowCount.setFlowData(
      {
          ...flowData.value,
          [props.detailObject.id]: {
              ...form,
              name: `${form.type}-${form.name}`,
          }
      }
  )
  // 触发数据更新事件
  // emit('update-data', {
  //   id: props.detailObject.id,
  //   data: form
  // });
  console.log("flowData",flowData.value);
  emit('cancel');

}
const cancel = () => {
  emit('cancel');
}

const toReader = () => {

}

const parseSql = () => {
}

const deleteField = () => {
  console.log('deleteField');
}

</script>

<style>

</style>